import pygame
import random


# 蛇类
# 点以20为单位
class Snake(object):
    # 初始化各种需要的属性 [开始时默认向右/身体块x5]
    def __init__(self, screen_x=1080, screen_y=720, grid_size=25):
        self.screen_x = screen_x
        self.screen_y = screen_y
        self.grid_size = grid_size
        self.dirction = pygame.K_RIGHT
        self.body = []
        for x in range(5):
            self.addnode()

    # 无论何时 都在前端增加蛇块
    def addnode(self):
        left, top = (0, 0)
        if self.body:
            left, top = (self.body[0][0].left, self.body[0][0].top)
        node = pygame.Rect(left, top, self.grid_size, self.grid_size)
        if self.dirction == pygame.K_LEFT:
            node.left -= self.grid_size
        elif self.dirction == pygame.K_RIGHT:
            node.left += self.grid_size
        elif self.dirction == pygame.K_UP:
            node.top -= self.grid_size
        elif self.dirction == pygame.K_DOWN:
            node.top += self.grid_size
        self.body.insert(0, [node, self.dirction])

    # 删除最后一个块
    def delnode(self):
        return self.body.pop()

    # 死亡判断
    def isdead(self):
        # 撞墙
        if self.body[0][0].x not in range(self.screen_x):
            return True
        if self.body[0][0].y not in range(self.screen_y):
            return True
        # 撞自己
        if self.body[0][0] in [node[0] for node in self.body[1:]]:
            return True
        return False

    # 移动！
    def move(self):
        self.addnode()
        return self.delnode()

    # 改变方向 但是左右、上下不能被逆向改变
    def changedirection(self, curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
        if curkey in LR + UD:
            if (curkey in LR) and (self.dirction in LR):
                return
            if (curkey in UD) and (self.dirction in UD):
                return
            self.dirction = curkey


# 食物类
# 方法： 放置/移除
# 点以20为单位
class Food:
    def __init__(self, screen_x=1200, screen_y=750, grid_size=25):
        self.screen_x = screen_x
        self.screen_y = screen_y
        self.grid_size = grid_size
        self.rect = pygame.Rect(-self.grid_size, 0, self.grid_size, self.grid_size)

    def remove(self):
        self.rect.x = -self.grid_size

    def set(self):
        if self.rect.x == -self.grid_size:
            allpos = []
            # 不靠墙太近 20 ~ SCREEN_X-20 之间
            for pos in range(self.grid_size, self.screen_x - self.grid_size, self.grid_size):
                allpos.append(pos)
            self.rect.left = random.choice(allpos)
            allpos = []
            for pos in range(self.grid_size, self.screen_y - 2 * self.grid_size, self.grid_size):
                allpos.append(pos)
            self.rect.top = random.choice(allpos)